package com.card.manager.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.card.framework.page.model.PageModel;
import com.card.framework.util.CommonUtil;
import com.card.manager.domain.Roles;
import com.card.manager.domain.Users;
import com.card.manager.services.RoleService;
import com.card.manager.services.UserService;
import com.card.manager.utils.Md5PwdEncoder;

@Controller
@RequestMapping("/user")
public class UsersController {

	@Autowired(required=true) 
	private UserService userServices;
	@Autowired(required=true) 
	private RoleService roleServices;
	
	@InitBinder
	public void setupDataBinder(WebDataBinder dataBinder) {
		//表单页面如果有时间类型的需要initbinder
		dataBinder.registerCustomEditor(String.class,new StringTrimmerEditor(false));  
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		dateFormat.setLenient(false);
		dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}
	@RequestMapping(value="/index")
	public String index(HttpServletRequest request,HttpSession session,
			HttpServletResponse response){
		return "userList";
	}
	@RequestMapping(value="/queryList",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> queryList(HttpServletRequest request,Users user,PageModel pageModel) throws Exception{
		SecurityContext sc = (SecurityContext)request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
		return userServices.selectUserForPage(sc.getAuthentication().getName(),user, pageModel);
	}
	/**
	 * 跳转到编辑页面<br>
	 * 根据id判断是新增还是修改
	 */
	@RequestMapping("/userUpdateWindow")
	public String userUpdateWindow(HttpServletRequest request,HttpSession session,
			HttpServletResponse response) throws IOException {
		String id = request.getParameter("id");
		Users user = null;
		if(StringUtils.isNotEmpty(id)){
			user = userServices.getById(Integer.parseInt(id));
			user.setRoles(roleServices.getUserRoles(user.getUserid()));
		}else{
			user = new Users();
			SecurityContext sc = (SecurityContext)request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
			user.setCreateuserid(sc.getAuthentication().getName());
		}
		List<Roles> roles = roleServices.allEnabledList();
		request.setAttribute("roleList",roles);
		request.setAttribute("user",user);
		return "/userPopWindow";
	}
	@RequestMapping("/userAddWindow")
	public String userAddWindow(HttpServletRequest request,HttpSession session,
			HttpServletResponse response) throws IOException {
		String id = request.getParameter("id");
		Users user = null;
		if(StringUtils.isNotEmpty(id)){
			user = userServices.getById(Integer.parseInt(id));
			user.setRoles(roleServices.getUserRoles(user.getUserid()));
		}else{
			user = new Users();
			SecurityContext sc = (SecurityContext)request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
			user.setCreateuserid(sc.getAuthentication().getName());
		}
		List<Roles> roles = roleServices.allEnabledList();
		request.setAttribute("roleList",roles);
		request.setAttribute("user",user);
		return "/userPopWindow";
	}
	/**
	 * 提交新增或修改,根据id是否为空判断.
	 * 返回提交成功后的数据.json格式
	 */
	@RequestMapping(value="/userUpdate",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, String> userUpdate(HttpServletRequest request,Users user) throws Exception{
		
		String[] userRoles = request.getParameterValues("userRoles");
		Set<Roles> roles = new HashSet<Roles>();
		if(userRoles != null)
			for(String str : userRoles){
				Roles role = new Roles();
				role.setRoleid(Integer.parseInt(str));
				roles.add(role);
			}
		user.setRoles(roles);
		Map<String, String> map = new HashMap<String, String>();
		try {
			if(user.getUserid() == null){
				if(!userServices.isExistUsername(user.getUsername())){
					user.setPassword(Md5PwdEncoder.encodePassword(user.getPassword()));
					userServices.insertUser(user);
					userServices.insertRoles(user.getUserid(), roles);
					map.put("result", "succ");
				}else{
					map.put("result", "fail");
					map.put("reason", "exists");
				}
			}else{
				userServices.updateUser(user);
				map.put("result", "succ");
			}
			
		}
		catch (Throwable e) {
			CommonUtil.throwsException(map, e);
		}
		return map; 
	}
	
	/**
	 * 提交新增或修改,根据id是否为空判断.
	 * 返回提交成功后的数据.json格式
	 */
	@RequestMapping(value="/userAdd",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, String> userAdd(HttpServletRequest request,Users user) throws Exception{
		
		String[] userRoles = request.getParameterValues("userRoles");
		Set<Roles> roles = new HashSet<Roles>();
		if(userRoles != null)
			for(String str : userRoles){
				Roles role = new Roles();
				role.setRoleid(Integer.parseInt(str));
				roles.add(role);
			}
		user.setRoles(roles);
		Map<String, String> map = new HashMap<String, String>();
		try {
			if(user.getUserid() == null){
				if(!userServices.isExistUsername(user.getUsername())){
					user.setPassword(Md5PwdEncoder.encodePassword(user.getPassword()));
					userServices.insertUser(user);
					userServices.insertRoles(user.getUserid(), roles);
					map.put("result", "succ");
				}else{
					map.put("result", "fail");
					map.put("reason", "exists");
				}
			}else{
				userServices.updateUser(user);
				map.put("result", "succ");
			}
			
		}
		catch (Throwable e) {
			CommonUtil.throwsException(map, e);
		}
		return map; 
	}
	
	@RequestMapping(value="/delete",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, String> delete(@RequestParam("json") String json){
		Map<String, String> map = new HashMap<String, String>();
		try {
			userServices.deleteUsers(CommonUtil.getBean(json, Users.class));
			map.put("mes", "删除成功");
		} catch (Throwable e) {
			CommonUtil.throwsException(map, e);
		}
		return map;//重定向
	}
}
